﻿using System;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.ServiceLocation;

namespace MyFramework.Helpers
{
    /// <summary>
    /// Event aggregator helper
    /// </summary>
    public static class EventAggregatorHelper
    {

        /// <summary>
        /// The event aggregator
        /// </summary>
        private static IEventAggregator eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();


        /// <summary>
        /// Subscribes to event.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="action">The action.</param>
        /// <param name="threadOption">The thread option.</param>
        /// <param name="filter">The filter.</param>
        public static void SubscribeToEvent<T, U>(Action<U> action, ThreadOption threadOption = ThreadOption.UIThread, Predicate<U> filter = null)
            where T : CompositePresentationEvent<U>, new()
        {
            T currentEvent = eventAggregator.GetEvent<T>();
            currentEvent.Subscribe(action, threadOption, false, filter != null ? filter : (e) => true);
        }

        /// <summary>
        /// Unsubscribes from event.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="action">The action.</param>
        public static void UnsubscribeFromEvent<T, U>(Action<U> action)
            where T : CompositePresentationEvent<U>, new()
        {
            T currentEvent = eventAggregator.GetEvent<T>();
            currentEvent.Unsubscribe(action);
        }

        /// <summary>
        /// Publishes the event.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="argument">The argument.</param>
        public static void PublishEvent<T, U>(U argument)
            where T : CompositePresentationEvent<U>, new()
        {
            T currentEvent = eventAggregator.GetEvent<T>();
            currentEvent.Publish(argument);
        }
    }
}
